/****************************************************
          File Name:shm_usage.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 25 Sep 2014 07:27:22 PM CST
*****************************************************/

#include"posix_ipc.h"
#define LEN 1024

int main(int argc, char * argv[])
{
    Usage(argc,"/shm",argv[0],argv[1]);

    int fd;
    void *addr;
    int flag=O_CREAT|O_RDWR;
    int port=PROT_READ|PROT_WRITE;
    int bytes;

    fd=shm_open(argv[1],flag,MODE);
    if(fd==-1)
        err("open");
    if(ftruncate(fd,LEN)==-1)
        err("ftruncate");
    
    addr=mmap(NULL,LEN,port,MAP_SHARED,fd,0);
    if(addr==(void *)-1)
        err("mmap");
    for(;;)
    {
        bytes=read(STDIN_FILENO,addr,LEN);
        if(bytes==0)
           break;
       if(bytes==-1)
          err("read"); 
        printf("%s",addr);
        if(memset(addr,0,LEN)==NULL)
            err("clean addr failed");
    }

    if(shm_unlink(argv[1])==-1)
        err("shm_unlink");
    if(munmap(addr,LEN)==-1)
        err("unmap failed");
    exit(EXIT_SUCCESS);
}
